/*  This file is part of YATracker.
    YATracker is free software: you can redistribute it and/or modify it under the terms
of the GNU Lesser General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
    YATracker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
    You should have received a copy of the GNU Lesser General Public License along with
YATracker. If not, see <http://www.gnu.org/licenses/>. */

#include <QDesktopWidget>
#include <QVBoxLayout>
#include <QSettings>
#include "main.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmapwidget.h"
#include "qgpssource.h"
#include "optionsdialog.h"
#include "yatsettings.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_followspot = false;
    statusBar()->addWidget(&m_statusLabelInfo, 600);

    QObject::connect(ui->actionStartStop, SIGNAL(triggered()), this, SLOT(gpsStartStop()));
    QObject::connect(ui->actionCenterSpot, SIGNAL(triggered()), this, SLOT(centerMapToSpot()));
    QObject::connect(ui->actionFollowSpot, SIGNAL(triggered()), this, SLOT(followSpot()));
    QObject::connect(ui->actionConfigure, SIGNAL(triggered()), this, SLOT(editPreferences()));

    m_MapWidget = new QMapWidget();

    QVBoxLayout *vboxlayout = new QVBoxLayout;
    vboxlayout->addWidget(m_MapWidget);
    ui->centralWidget->setLayout(vboxlayout);

    if (!m_yatmapfile.open("..\\test.yat"))
    {
        alertWarn("Failed to load map file.");
    }
    m_MapWidget->setMapFile(&m_yatmapfile);

    QString portName(YATSettings::serialPortName());
    portName.insert(0, "\\\\.\\");
    m_gps = new QGpsSource();
    m_gps->setComPort(portName);

    QObject::connect(m_gps, SIGNAL(gpsMessageRMC(double,double)), this, SLOT(gpsMessageRMC(double,double)));
    QObject::connect(m_gps, SIGNAL(gpsMessageGGA(int,double,double,int)), this, SLOT(gpsMessageGGA(int,double,double,int)));
    QObject::connect(m_gps, SIGNAL(gpsMessageGSA(int,float,float,float,int)), this, SLOT(gpsMessageGSA(int,float,float,float,int)));

    updateGpsStatus();
}

MainWindow::~MainWindow()
{
    delete m_gps;
    delete m_MapWidget;
    delete ui;
}

void MainWindow::restoreSettings()
{
    restoreGeometry(Global_getSettings()->value("MainWindow/Geometry").toByteArray());
    restoreState(Global_getSettings()->value("MainWindow/WindowState").toByteArray());
}

void MainWindow::closeEvent(QCloseEvent *)
{
    Global_getSettings()->setValue("MainWindow/Geometry", saveGeometry());
    Global_getSettings()->setValue("MainWindow/WindowState", saveState());
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::gpsStartStop()
{
    if (m_gps->isConnected())
    {
        m_gps->gpsClose();
    }
    else
    {
        if (!m_gps->gpsConnect())
        {
            alertWarn("Failed to connect to GPS.");
            ui->actionStartStop->setChecked(false);
        }
    }

    updateGpsStatus();
}

void MainWindow::editPreferences()
{
    OptionsDialog dlg(this);
    dlg.exec();
}

void MainWindow::gpsMessageRMC(double latitude, double longitude)
{
    m_lasttimedatareceived = QDateTime::currentDateTime();
    updateGpsStatus();
    m_MapWidget->setSpotPosition(latitude, longitude);
    if (m_followspot)
        m_MapWidget->setTargetPosition(latitude, longitude);
}
void MainWindow::gpsMessageGSA(int fix, float pdop, float hdop, float vdop, int fixSats)
{
    m_lasttimedatareceived = QDateTime::currentDateTime();
    updateGpsStatus();
}
void MainWindow::gpsMessageGGA(int fix, double latitude, double longitude, int fixSats)
{
    m_lasttimedatareceived = QDateTime::currentDateTime();
    updateGpsStatus();
}

void MainWindow::updateGpsStatus()
{
    QString status;
    if (!m_gps->isConnected())
        status = "Not connected";
    else
    {
        if (m_lasttimedatareceived.addMSecs(1500) < QDateTime::currentDateTime())
            status = "No data";
        else
            status = "OK";
    }

    status.insert(0, "GPS: ");
    m_statusLabelInfo.setText(status);
}

void MainWindow::centerMapToSpot()
{
    m_MapWidget->centerToSpot();
}
void MainWindow::followSpot()
{
    m_followspot = ui->actionFollowSpot->isChecked();
    if (m_followspot)
        m_MapWidget->centerToSpot();
    else
        m_MapWidget->resetTargetPosition();
}
